import { getApps } from './index'
import { importHTML } from './import-html';
import { getNextRoute, getPrevRoute } from './watch-router'

export const handleRouter = async ()=> {
    // 1. 获取当前路由路径，去apps里查找
    const apps = getApps()
    // 2. 获取上一个路由
    const prevApp = apps.find(item => {
        return getPrevRoute().startsWith(item.activeRule)
    })
    const app = apps.find(app => getNextRoute().startsWith(app.activeRule))
    if(prevApp) {
        await unmount(prevApp)
    }
    console.log(app)
    if(!app) return 

    // 3. 加载子应用
    const { template , execScripts }  = await importHTML(app.entry)
    const container = document.querySelector(app.container)
    container.appendChild(template)

    window.__POWERED_BY_QIANKUN__ = true
    window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ = app.entry + '/'

    const appExports = await execScripts()

    app.bootstrap = appExports.bootstrap
    app.mount = appExports.mount
    app.unmount = appExports.unmount

    // 4.渲染子应用
    
    await bootstrap(app)
    await mount(app)

    async function bootstrap(app) {
        app.bootstrap && (await app.bootstrap())
    }
    async function mount(app) {
        let container = document.querySelector(app.container)
        console.log(container)
        app.mount && (await app.mount({
            container
        }))
    }
    async function unmount(app) {
        let container = document.querySelector(app.container)
        app.unmount && (await app.unmount({
            container
        }))
        container.innerHTML = ''
    }
}


